package com.oromwin.repos.socket.request.file;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Common;
import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.Common.ReposResult;
import com.oromwin.repos.common.helper.DBHelper;
import com.oromwin.repos.common.helper.FSHelper;
import com.oromwin.repos.common.helper.IOHelper;
import com.oromwin.repos.data.AbstractReposTable;
import com.oromwin.repos.data.FileTable;
import com.oromwin.repos.server.LockObject;
import com.oromwin.repos.socket.request.AbstractRequest;
import com.oromwin.repos.socket.request.RequestAction;
import com.oromwin.repos.socket.response.Response;
import com.oromwin.repos.socket.response.file.ReadFileResponse;

public class ReadFileRequest extends AbstractRequest implements RequestAction {
    private Log log = Logger.getLog(ReadFileRequest.class);
    private String VolumeName = null;
    private String FileId = null;
    private File LocalPath = null;
    
    public ReadFileRequest() {
    }
    
    public ReadFileRequest(String volumeName, String fileId, File localPath) {
        VolumeName = volumeName;
        FileId = fileId;
        LocalPath = localPath;
    }

    @Override
    public void receive(DataInputStream dis, LockObject lockObject) throws ReposException {
        try {
            synchronized (lockObject) {
                VolumeName = IOHelper.readUTF8(dis);
                FileId = IOHelper.readUTF8(dis);
                LocalPath = new File(IOHelper.readUTF8(dis));
            }
        } catch (IOException e) {
            String message = String.format("Failed to read stream, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
    }

    @Override
    public Response run() {
        ReadFileResponse res = null;
        File file = null;
        try {
            _fileTable = (FileTable) getCurrentReposTable();
            checkSameObjectExists();
            file = _fileTable.getFullFilepath();
            res = new ReadFileResponse(ReposResult.Success, "Succeeded to read file", file, LocalPath);
        } catch (ReposException e) {
            res = new ReadFileResponse(ReposResult.Failure, e.getMessage(), file, LocalPath);
        }
        return res;
    }
    
    @Override
    public void send(DataOutputStream dos) throws ReposException {
        try {
            IOHelper.writeUTF8(dos, this.getClass().getCanonicalName());
            IOHelper.writeUTF8(dos, VolumeName);
            IOHelper.writeUTF8(dos, FileId);
            IOHelper.writeUTF8(dos, LocalPath.toString());
            dos.flush();
        } catch (IOException e) {
            String message = String.format("Failed to write into output stream, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
    }
    
    @Override
    public void checkFreeSpaceExists() throws ReposException {
        throw ReposException.create(log, Common.Message.NOT_IMPLEMENTED_METHOD_INVOKE);
    }

    @Override
    public void checkSameObjectExists() throws ReposException {
        File file = _fileTable.getFullFilepath();
        if (!FSHelper.ls(file)) {
            String message = String.format("Requested file does not exist on the server, path {%s}", file);
            throw ReposException.create(log, message);
        }
    }

    @Override
    public void checkDependentObjectNotExists() throws ReposException {
        throw ReposException.create(log, Common.Message.NOT_IMPLEMENTED_METHOD_INVOKE);
    }

    @Override
    public AbstractReposTable getCurrentReposTable() throws ReposException {
        AbstractReposTable reposTable = null;
        String whereClause = String.format("FileStatus < 2 AND FileId = '%s'", FileId);
        List<AbstractReposTable> reposTables = DBHelper.selectTable(FileTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("'%s' FileId does not exists in database, VolumeName:tableSize:whereClause {%s:%d:%s}", FileId, VolumeName, reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        return reposTable;
    }

    @Override
    public AbstractReposTable getParentReposTable() throws ReposException {
        throw ReposException.create(log, Common.Message.NOT_IMPLEMENTED_METHOD_INVOKE);
    }

}
